//
//  MyXMPP.m
//  xmpp
//
//  Created by welldone on 13-8-7.
//  Copyright (c) 2013年 net.koina. All rights reserved.
//

#import "MyXMPP.h"
#import <Foundation/Foundation.h>
#import "Connect.h"
#import "XMPPFramework.h"
#import "CheckNetWorkTool.h"
#import "StringTool.h"
#import "UserModal.h"
#import "API.h"
#import "PushDM.h"
#import "JSONKit.h"
#import "MessageModel.h"
#import "XMLReader.h"
#import "Tools.h"




//chat
#define kUserName    @"xmppUserName"
#define kPassword    @"xmppPassword"
#define kDomain      @"in"






typedef enum : NSUInteger {
    UserStatyNotAuth=1,
    UserStatyOffLine,
    UserStatyOnLine,
    UserStatyErr
} UserStaty;

@interface MyXMPP ()<XMPPStreamDelegate>
+(UserStaty)haveRegist:(NSString*)jid;
@end


@implementation MyXMPP


+ (MyXMPP *)sharedMyXMPP {
    
    static MyXMPP *sharedMyXMPP;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyXMPP = [[self alloc] init];
    });
    
    
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *islogin = [defaults objectForKey:@"login"] ;
    NSString *userCode = [UserModal shareUserModel].userCode;
    
    if ([StringTool isBlankString:userCode]==false&&[islogin isEqualToString:@"YES"]) {
        
        [[NSUserDefaults standardUserDefaults]setObject:userCode forKey:kUserName];
        [[NSUserDefaults standardUserDefaults]setObject:[userCode MD5Hash] forKey:kPassword];
        //            [[NSUserDefaults standardUserDefaults]setObject:@"192.168.2.84" forKey:kServerHost];
        [[NSUserDefaults standardUserDefaults]synchronize];
        
    }else{
        
        [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:kUserName];
        [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:kPassword];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
    
    return sharedMyXMPP;
}



#pragma mark - self
- (void)setupStream {
    
    self.xmppStream = [[XMPPStream alloc] init];
    [self.xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    XMPPMessageDeliveryReceipts *xmppMessageDeliveryRecipts = [[XMPPMessageDeliveryReceipts alloc] initWithDispatchQueue:dispatch_get_main_queue()];
    xmppMessageDeliveryRecipts.autoSendMessageDeliveryReceipts = YES;
    xmppMessageDeliveryRecipts.autoSendMessageDeliveryRequests = YES;
    [xmppMessageDeliveryRecipts activate:self.xmppStream];
}

- (void)goOnline {
    XMPPPresence *presence = [XMPPPresence presence];
    [[self xmppStream] sendElement:presence];
}

- (void)goOffline {
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
    [[self xmppStream] sendElement:presence];
}


- (void)sendMessage:(NSString *)txtStr toUser:(NSString *) user {
    
    NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:txtStr];
    
    NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
    [message addAttributeWithName:@"id" stringValue:[self.xmppStream generateUUID]];
    [message addAttributeWithName:@"type" stringValue:@"chat"];
    [message addAttributeWithName:@"to" stringValue:user];
    [message addChild:body];
    
    [self.xmppStream sendElement:message];
}



- (BOOL)connect {
    
    NSString *jabberID = [[NSUserDefaults standardUserDefaults] stringForKey:kUserName];
    NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:kPassword];
    
    if ([StringTool isBlankString:jabberID]) {
        return false;
    }
    
    if (!self.xmppStream) {
        [self setupStream];
    }
    
    if (![self.xmppStream isDisconnected]) {
        
        if (![self.xmppStream isAuthenticated]) {
            [self xmppStreamDidConnect:self.xmppStream];
        }
        
        return YES;
    }
    
    if (jabberID == nil || myPassword == nil) {
        
        return NO;
    }
    
    
    jabberID = [NSString stringWithFormat:@"%@@%@",jabberID,SERVER_NAME];
    
    XMPPJID *my = [XMPPJID jidWithString:jabberID];
    NSString *nick = @"res";
    my = [my jidWithNewResource:nick];
    
    [self.xmppStream setMyJID:my];
    [self.xmppStream setHostName:SERVER_IP];
    //    [self.xmppStream setHostPort:10010];
    
    
    if(![CheckNetWorkTool isExistenceNetwork]){
        
        [self xmppStateDelegateCallBack:@"没有网络连接"];
        
        return false;
    }else{
        
        [self xmppStateDelegateCallBack:@"正在连接..."];
    }
    
    
    
    NSError *error = nil;
    if (![self.xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
    {
        NSLog(@"%@",@"Can't connect to server");
        return NO;
    }
    
    return YES;
}





- (void)disconnect {
    
    [self goOffline];
    [self.xmppStream disconnect];
}





-(void)xmppStateDelegateCallBack:(NSString*)state{
    
    if ([self.delegate respondsToSelector:@selector(xmppStateChange:)]) {
        [self.delegate xmppStateChange:state];
    }
}


+(UserStaty)haveRegist:(NSString*)jid{
    
    jid = [NSString stringWithFormat:@"%@@%@",jid,SERVER_NAME];
    
    //    NSString *url = [NSString stringWithFormat:@"http://%@:9090/plugins/presence/status?jid=%@&type=xml",SERVER_IP,jid];
    NSString *url = [NSString stringWithFormat:@"http://%@/presence/status?jid=%@&type=xml",PD_SERVER_IP,jid];
    
    NSString *res = [Connect doGetWithOutCaChe:url].resultData;
    
    NSRange range1 = [res rangeOfString:@"error"];//判断字符串是否包含
    NSRange range2 = [res rangeOfString:@"403"];//判断字符串是否包含
    NSRange range3 = [res rangeOfString:@"auth"];//判断字符串是否包含
    
    if ((range1.length >0&&range2.length >0&&range3.length >0)){
        return UserStatyNotAuth;
    }else if([res rangeOfString:@"type=\"unavailable\""].length>0){
        return UserStatyOffLine;
    }else{
        return UserStatyOnLine;
    }
}


-(Boolean)isReceiveBackMsg:(XMPPMessage*)message{
    
    NSXMLElement *element = [message elementForName:@"received"];
    if (element&&[element.xmlns isEqualToString:@"urn:xmpp:receipts"]) {
        
        NSString *msgId = [[element attributeForName:@"id"] stringValue];
        if (msgId) {
            return true;
        }
    }
    return false;
}



#pragma mark - XMPP Delegate

- (void)xmppStreamDidConnect:(XMPPStream *)sender {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        
        NSString *MyJabberID = [[NSUserDefaults standardUserDefaults] stringForKey:kUserName];
        
        UserStaty userStaty = [MyXMPP haveRegist: MyJabberID];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            [self xmppStateDelegateCallBack:@"正在登录..."];
            
            NSError *error = nil;
            if (userStaty!=UserStatyNotAuth) {
                
                [self.xmppStream authenticateWithPassword:[[NSUserDefaults standardUserDefaults] objectForKey:kPassword] error:&error];
            }else{
                
                [self xmppUserReg];
                
            }
        });
    });
}



- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
    NSLog(@"%@",[error description]);
    
    [self xmppStateDelegateCallBack:@"登录失败"];
}


- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender {
    
    [self xmppStateDelegateCallBack:@""];//suceFull
    
    [self goOnline];
}


- (void)xmppUserReg{
    
    [self xmppStateDelegateCallBack:@"正在注册..."];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *jabberID = [[NSUserDefaults standardUserDefaults] stringForKey:kUserName];
        NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:kPassword];
        
        
        NSString *url = [NSString stringWithFormat:@"http://%@/wgf-app-im/user/create",REG_SERVER_IP];
        
        NSMutableDictionary *dicc = [[NSMutableDictionary alloc]init];
        [dicc setObject:jabberID forKey:@"userName"];
        [dicc setObject:myPassword forKey:@"passWord"];
        [dicc setObject:[PushDM getPushToken] forKey:@"deviceToken"];
        [dicc setObject:@"IOS" forKey:@"deviceType"];
        [dicc setObject:@"QQ" forKey:@"fromApp"];
        
        ResulteMod *mod = [Connect doPostOutCaCheWithUrl:url withParamDic:dicc];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if([mod.resultCode isEqualToString:@"20003"]){
                
                [self xmppStateDelegateCallBack:@"正在登录..."];
                
                
                NSError *error = nil;
                [self.xmppStream authenticateWithPassword:[[NSUserDefaults standardUserDefaults] objectForKey:kPassword] error:&error];
                
            }else{
                [self xmppStateDelegateCallBack:@"注册失败!"];
            }
        });
    });
}


- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error{
    
    NSError *err = nil;
    [self.xmppStream registerWithPassword:[[NSUserDefaults standardUserDefaults] objectForKey:kPassword] error:&err];
}



#pragma mark xmpp  did Receive
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence {
    
    XMPPJID*my1 = sender.myJID;
//    XMPPJID*my2 = self.xmppStream.myJID;
    
    XMPPJID*from = [presence from];
//    XMPPJID*to = [presence to];
    
    NSString *presenceType = [presence type]; // online/offline
//    NSString *myUsername = [my1 user];
    NSString *presenceFromUser = [from user];
    
    
    if ([presenceType isEqualToString:@"available"]) {
        
        if ([self.delegate respondsToSelector:@selector(newBuddyOnline:)]) {
            
            [self.delegate newBuddyOnline:[NSString stringWithFormat:@"%@@%@", presenceFromUser, kDomain]];
        }
        
    } else if ([presenceType isEqualToString:@"unavailable"]) {
        
        if ([self.delegate respondsToSelector:@selector(buddyWentOffline:)]) {
            
            [self.delegate buddyWentOffline:[NSString stringWithFormat:@"%@@%@", presenceFromUser, kDomain]];
        }
    }
}



#pragma mark xmpp  did Receive
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message {
    
    
    if ([message isChatMessageWithBody]) {
        
        NSString *from = [[message attributeForName:@"from"] stringValue];
        from = [[from componentsSeparatedByString:@"/"] objectAtIndex:0];
        
//        NSString *to = [[message attributeForName:@"to"] stringValue];
//        to = [[to componentsSeparatedByString:@"/"] objectAtIndex:0];
        
//        NSString *msgId = [[message attributeForName:@"id"] stringValue];
        
//        NSString *msgTitle = [[message elementForName:@"subject"] stringValue];
        NSString *msgBody = [[message elementForName:@"body"] stringValue];
        
        
        if ([from isEqualToString:@"broadcast@im.wgfcdn.com"]) {//Broadcast
            
            MessageModel *msg = [MessageModel new];
            [msg setMessageSub:msgBody];
            [msg setMessageTime:[Tools getNowDate]];
            
            NSString *str = [NSString stringWithFormat:@"%@",message];
            NSError *parseError = nil;
            NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:str error:&parseError];
            xmlDictionary = [xmlDictionary objectForKey:@"message"];
            xmlDictionary = [xmlDictionary objectForKey:@"properties"];
            NSArray *parm = [xmlDictionary objectForKey:@"property"];
            
            
            for (NSDictionary *dic in parm) {
                
                NSString *sty = [[dic objectForKey:@"name"] objectForKey:@"text"];
                
                if ([sty isEqualToString:@"t"]) {
                    NSString *msgType = @"0";
                    NSDictionary *dv = [dic objectForKey:@"value"];
                    msgType = [dv objectForKey:@"text"];
                    
                    if ([msgType isEqualToString:@"0"]) {
                        [msg setMessageType:MessageTypeSYS];
                        [msg setMessageTitle:@"系统消息"];
                    }else if ([msgType isEqualToString:@"1"]){
                        [msg setMessageType:MessageTypeACTIVITY];
                        [msg setMessageTitle:@"楼盘活动"];
                    }else if ([msgType isEqualToString:@"2"]){
                        [msg setMessageType:MessageTypeORDER];
                        [msg setMessageTitle:@"交易通知"];
                    }else{
                        [msg setMessageType:MessageTypeSYS];
                        [msg setMessageTitle:@"系统消息"];
                    }
                    
                }else if([sty isEqualToString:@"v"]){
                    
                    NSString *msgValue = @"0";
                    NSDictionary *dv = [dic objectForKey:@"value"];
                    msgValue = [dv objectForKey:@"text"];
                    [msg setMessageValue:msgValue];
                }
            }
            
            
            if ([self.delegate respondsToSelector:@selector(newMessageReceived:)]) {
                
                [self.delegate newMessageReceived:msg];
            }
        }
        
    }else if([self isReceiveBackMsg:message]){
        
        NSXMLElement *element = [message elementForName:@"received"];
        if (element) {
            
//            NSString *from = [[message attributeForName:@"from"] stringValue];
//            from = [[from componentsSeparatedByString:@"/"] objectAtIndex:0];
            
//            NSString *to = [[message attributeForName:@"to"] stringValue];
//            to = [[to componentsSeparatedByString:@"/"] objectAtIndex:0];
            
//            NSString *msgId = [[element attributeForName:@"id"] stringValue];
        }
    }
    
}



#pragma mark xmpp  did Receive
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq{

    return NO;
}


- (void)xmppStream:(XMPPStream *)sender didReceiveError:(NSXMLElement *)error{
    
    NSLog(@"didReceiveError:%@",error);
    DDXMLNode *errorNode = (DDXMLNode *)error;
    //遍历错误节点
    for(DDXMLNode *node in [errorNode children])
    {
        //若错误节点有【冲突】
        if([[node name] isEqualToString:@"conflict"])
        {
            NSString *message = @"别处登录";
            [self xmppStateDelegateCallBack:message];
        }
    }
}








@end
